<?php

/**
 * 分类管理 - 管理后台
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\admin\controller\system;

use app\admin\Controller;
use think\Db;
use think\Exception;

class Type extends Controller
{

    use \app\admin\traits\controller\Controller;

    protected static $blacklist = ['deleteforever', 'clear'];
    protected $pid = 0; //父结点

    /**
     * 配置管理
     */

    public function fields()
    {
        $id = $this->request->get("id", 0, 'intval');
        if (!$id) {
            throw new Exception('缺少必要参数ID');
        }

        $map = ['id' => $id, 'isdelete' => 0, 'pid' => 0];
        $item = Db::name("type")->where($map)->field('fields')->find();
        if (!$item) {
            return 'no auth';
        }

        if ($this->request->isAjax()) {
            $rs = \Fields::request("form", "post");
            if (is_array($rs)) {
                $save = ['fields' => json_encode($rs)];
                Db::name("type")->where($map)->update($save);
                return ajax_return_adv('添加成功');
            } else {
                throw new Exception((string) $rs ?: "未知错误");
            }
        }

        return widget("Fields/editor", [$item['fields'], request()->url()]);
    }
    
    /**
     * 加载节点名称
     */
    public function load_item_name()
    {
        $ids = array_unique(explode(",", $this->request->param('ids')));
        $data = Db::name('type')->where('id', 'in', $ids)->column('name', 'id');
        return json($data);
    }

    /**
     * 设置默认排序规则
     */
    protected function beforeIndex()
    {
        $_GET['_order'] = 'sort';
        $_GET['_sort'] = 'asc';
    }

    protected function beforeAdd()
    {
        $this->view->assign("pid", $this->pid);
    }
    
    protected function successAdd()
    {
        $this->clearCache();
    }
    
    protected function successEdit()
    {
        $this->clearCache();
    }
    
    protected function successForbid()
    {
        $this->clearCache();
    }
    
    protected function successResume()
    {
        $this->clearCache();
    }
    
    private function clearCache()
    {
        \Fields::clearCache();
    }

    /**
     * 重置搜索框
     * @param object $model
     */
    protected function search($model)
    {
        $map = [];
        $map['pid'] = $this->pid;
        return $map;
    }

}
